<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="small"
          @click="handleAdd"
          v-hasPermi="['course:video:add']"
        >上传视频</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="small"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['course:video:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="5">
        <el-select
          v-model="queryParams.chapterId"
          placeholder="请选择"
          size="small"
          @change="changeChapter"
        >
          <el-option
            v-for="chapter in chapterList"
            :value="chapter.chapterId+''"
            :label="chapter.chapterName"
          ></el-option>
        </el-select>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="videoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="视频名称"
        align="center"
        prop="video.videoName"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="视频封面"
        align="center"
        prop="video.videoCover"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">
          <el-image
            class="videoImg"
            :src="scope.row.video.videoCover"
            :preview-src-list="[scope.row.video.videoCover]"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column label="视频大小" align="center" prop="video.videoSize">
        <template slot-scope="scope">
          <span>{{byte2mb(scope.row.video.videoSize)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="时长" align="center" prop="video.videoDuration">
        <template slot-scope="scope">
          <span>{{formatSecond(scope.row.video.videoDuration)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="播放次数" align="center" prop="video.videoPlayCount" />
      <el-table-column label="播完次数" align="center" prop="video.videoFinishCount" />
      <el-table-column label="是否可以快进" align="center" prop="isForward">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.video_is_forward" :value="scope.row.isForward" />
        </template>
      </el-table-column>
      <el-table-column label="视频状态" align="center" prop="video.videoStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.video_status" :value="scope.row.video.videoStatus" />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="video.createTime" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.video.createTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改时间" align="center" prop="video.updateTime" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.video.updateTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row.video)"
            v-hasPermi="['course:video:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row.video)"
            v-hasPermi="['course:video:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-video-play"
            @click="handleView(scope.row.video)"
          >预览视频</el-button>
          <el-tooltip
            class="item"
            effect="dark"
            content="视频在播放第多少秒时弹出题目,防止用户挂机"
            placement="top-end"
          >
            <el-button
              size="mini"
              type="text"
              icon="el-icon-document"
              @click="handleBingQuList(scope.row.id,scope.row.video.videoDuration)"
            >绑定题目</el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 预览视频 -->
    <el-dialog :title="title" :visible.sync="openView" width="800px" append-to-body>
      <VideoPlayer v-if="openView" :videoInfo="videoWatch" />
    </el-dialog>

    <!-- 上传视频对话框 -->
    <el-dialog :title="title" :visible.sync="openAdd" width="500px" append-to-body>
      <video-upload
        @uploadFinish="uploadFinish"
        :fileSize="1024"
        :fileType="videoType"
        :chapterId="queryParams.chapterId+''"
      />
    </el-dialog>

    <!-- 修改视频对话框 -->
    <el-dialog :title="title" :visible.sync="openEdit" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px" label-position="top">
        <el-form-item label="视频名称" prop="videoName">
          <el-input v-model="form.videoName" placeholder="请输入视频名称" />
        </el-form-item>
        <el-form-item label="视频封面" prop="videoCover">
          <image-upload v-model="form.videoCover" :fileSize="2" />
        </el-form-item>
        <el-form-item label="是否可以快进" prop="videoCover">
          <el-switch
            v-model="form.isForward"
            :inactive-value="0"
            :active-value="1"
            active-color="#13ce66"
            inactive-color="#ff4949"
            inactive-text="禁止快进"
            active-text="允许快进"
          ></el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 绑定题目 -->
    <el-drawer title="视频已绑定的题目列表!" :visible.sync="question.bind" direction="rtl" size="50%">
      <el-tooltip class="item" effect="dark" content="视频在播放第多少秒时弹出题目,防止用户挂机" placement="top-start">
        <el-button type="primary" plain class="bindBtn" @click="handleUnBindQuList">绑定题目</el-button>
      </el-tooltip>
      <el-table v-loading="loading" :data="bindQuList">
        <el-table-column
          label="题干内容"
          align="center"
          prop="objContent"
          :show-overflow-tooltip="true"
        />
        <el-table-column label="题目类型" align="center" prop="objType">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.obj_qu_type" :value="scope.row.objType" />
          </template>
        </el-table-column>
        <el-table-column
          label="难度等级"
          align="center"
          prop="objGrand"
          width="160"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            <el-rate v-model="scope.row.objGrand" disabled></el-rate>
          </template>
        </el-table-column>
        <el-table-column label="知识点" align="center" prop="objTag" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <my-tag :valStr="scope.row.objTag"></my-tag>
          </template>
        </el-table-column>
        <el-table-column label="第多少秒弹出题目" align="center" prop="second" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleVideoQuRemove(scope.row)"
              v-hasPermi="['course:chapter:edit']"
            >解绑</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleQuInfo(scope.row)"
            >详情</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-drawer>

    <el-dialog title="视频未绑定的题目列表!" :visible.sync="question.unBind" width="50%" append-to-body>
      <el-form
        :model="unBindQuQuery"
        ref="unBindQuQueryForm"
        size="medium"
        :inline="true"
        v-show="showSearch"
        label-width="68px"
      >
        <el-form-item prop="searchValue">
          <el-input
            v-model="unBindQuQuery.searchValue"
            placeholder="请输入题干内容/知识点"
            clearable
            @keyup.enter.native="handleQueryUnBindQu"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="medium"
            @click="handleQueryUnBindQu"
          >搜索</el-button>
          <el-button icon="el-icon-refresh" size="medium" @click="resetUnBindQuQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="20" class="mb8">
        <el-col :span="10">
          <div class="inner-select">
            <span>题目类型：</span>
            <el-select
              v-model="unBindQuQuery.quType"
              placeholder="请选择"
              size="small"
              @change="changeUnBindQuType"
              :clearable="true"
            >
              <el-option
                v-for="dict in dict.type.obj_qu_type"
                :value="dict.value"
                :label="dict.label"
              ></el-option>
            </el-select>
          </div>
        </el-col>
        <el-col :span="10">
          <div class="inner-select">
            <span>难度等级：</span>
            <el-select
              v-model="unBindQuQuery.quGrand"
              placeholder="请选择"
              size="small"
              @change="changeUnBindQuGrand"
              :clearable="true"
            >
              <el-option
                v-for="dict in dict.type.qu_qu_grand"
                :value="dict.value"
                :label="dict.label"
              ></el-option>
            </el-select>
          </div>
        </el-col>
      </el-row>

      <el-table v-loading="loading" :data="unBindQuList">
        <el-table-column
          label="题干内容"
          align="center"
          prop="objContent"
          :show-overflow-tooltip="true"
        />
        <el-table-column label="题目类型" align="center" prop="objType">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.obj_qu_type" :value="scope.row.objType" />
          </template>
        </el-table-column>
        <el-table-column label="难度等级" align="center" prop="objGrand" width="200">
          <template slot-scope="scope">
            <el-rate v-model="scope.row.objGrand" disabled></el-rate>
          </template>
        </el-table-column>
        <el-table-column label="知识点" align="center" prop="objTag" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <my-tag :valStr="scope.row.objTag"></my-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-plus"
              @click="handleVideoQuAdd(scope.row.objId)"
              v-hasPermi="['course:chapter:add']"
            >绑定</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleQuInfo(scope.row)"
            >详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="unBindQuTotal>0"
        :total="unBindQuTotal"
        :page.sync="unBindQuQuery.pageNum"
        :limit.sync="unBindQuQuery.pageSize"
        @pagination="getUnBindQuList"
      />
    </el-dialog>

    <el-dialog title="选择视频第多少秒弹出题目!" :visible.sync="secondSelect" width="40%" append-to-body>
      <el-form label-width="120px" label-position="top">
        <el-form-item label="第多少秒" prop="second">
          <el-slider
            v-model="second"
            :min="0"
            :max="videoDuration"
            :step="60"
            show-stops
            show-input
          ></el-slider>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAddQu">确 定</el-button>
        <el-button @click="cancelAddQu">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 弹出详细信息弹窗 -->
    <obj-info :visible.sync="infoDialog.objShow" :objInfo="infoDialog.objData" />
  </div>
</template>

<script>
import { delVideo } from "@/api/course/video";
import {
  listSimpleChapter,
  chapterVideoList,
  chapterVideoInfo,
  updateChapterVideo,
  videoBindQuList,
  videoUnBindQuList,
  videoDelQu,
  videoAddQu
} from "@/api/course/chapter";
import VideoPlayer from "@/components/VideoPlayer/index.vue";
import ObjInfo from "@/components/QuInfo/objInfo";
export default {
  name: "Video",
  dicts: ["video_status", "video_is_forward", "obj_qu_type", "qu_qu_grand"],
  components: {
    VideoPlayer,
    ObjInfo
  },
  data() {
    return {
      // infoDialog
      infoDialog: {
        objShow: false,
        objData: {}
      },
      // 题目id
      objId: 0,
      // 视频最大秒数
      videoDuration: 0,
      // 选择时间
      second: 1,
      // 选择时间弹框
      secondSelect: false,
      // 章节视频对应id
      id: undefined,
      // 未绑定题目数量
      unBindQuTotal: 0,
      // 未绑定题目列表
      unBindQuList: [],
      // 视频未绑定题目查询
      unBindQuQuery: {
        id: undefined,
        quGrand: undefined,
        quType: undefined,
        searchValue: undefined,
        pageSize: 10,
        pageNum: 1
      },
      // 已绑定题目列表
      bindQuList: [],
      // 绑定题目弹框
      question: {
        bind: false,
        unBind: false
      },
      // 视频类型
      videoType: ["mp4", "mkv", "avi"],
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 视频表格数据
      videoList: [],
      // 弹出层标题
      title: "",
      // 是否显示上传弹出层
      openAdd: false,
      // 是否显示修改弹出层
      openEdit: false,
      // 弹出视频预览
      openView: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        chapterId: 0
      },
      // 课程视频预览信息
      videoWatch: {
        videoUrl: "",
        videoCover: ""
      },
      // 课程id
      courseId: 0,
      // 章节信息
      chapterList: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        videoName: [
          { required: true, message: "视频名称不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    let courseId = this.$route.params.courseId;
    let chapterId = this.$route.params.chapterId;
    this.courseId = courseId;
    this.queryParams.chapterId = chapterId;
    // 获取章节简易信息列表
    this.getChapterList();
    this.getList();
  },
  methods: {
    /** byte转mb */
    byte2mb(b) {
      return (b / 1024 / 1024).toFixed(2) + "MB";
    },
    /** 下拉更改章节 */
    changeChapter() {
      this.getList();
    },
    /** 获取章节简易信息列表 */
    getChapterList() {
      listSimpleChapter({ courseId: this.courseId })
        .then(res => {
          if (res.code === 200) {
            this.chapterList = res.data;
          }
        })
        .finally(() => {});
    },
    /** 查询视频列表 */
    getList() {
      this.loading = true;
      chapterVideoList(this.queryParams).then(response => {
        this.videoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.openEdit = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        videoId: 0,
        videoName: "",
        videoCover: "",
        isForward: 0,
        chapterId: this.queryParams.chapterId
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.videoId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.openAdd = true;
      this.title = "上传视频";
    },
    /** 修改按钮操作 */
    handleUpdate(video) {
      this.loading = true;
      this.reset();
      const videoId = video.videoId || this.ids;
      chapterVideoInfo({
        videoId: videoId,
        chapterId: this.queryParams.chapterId
      }).then(response => {
        this.loading = false;
        this.form.videoCover = response.data.video.videoCover;
        this.form.videoName = response.data.video.videoName;
        this.form.isForward = response.data.isForward;
        this.form.videoId = response.data.video.videoId;
        this.openEdit = true;
        this.title = "修改视频信息";
      });
    },
    /** 预览视频 */
    handleView(video) {
      this.openView = true;
      this.title = video.videoName;
      this.videoWatch.videoUrl = video.videoUrl;
      this.videoWatch.videoCover = video.videoCover;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          updateChapterVideo(this.form)
            .then(response => {
              this.$modal.msgSuccess("修改成功");
              this.openEdit = false;
              this.getList();
            })
            .finally(() => {
              this.buttonLoading = false;
            });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(video) {
      const videoIds = video.videoId || this.ids;
      this.$modal
        .confirm('是否确认删除视频编号为"' + videoIds + '"的数据项？')
        .then(() => {
          this.loading = true;
          return delVideo(videoIds);
        })
        .then(() => {
          this.loading = false;
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .finally(() => {
          this.loading = false;
        });
    },
    /** 视频时长格式化 */
    formatSecond(s) {
      let minute = parseInt(s / 60);
      s = s % 60;
      return minute + "分" + s + "秒";
    },
    /** upload完成 */
    uploadFinish() {
      this.openAdd = false;
      this.getList();
    },
    /** 视频绑定题目列表 */
    handleBingQuList(id, videoDuration) {
      this.question.bind = true;
      this.loading = true;
      this.unBindQuQuery.id = id;
      this.id = id;
      this.videoDuration = videoDuration;
      this.getBindQuList(id);
    },
    getBindQuList(id) {
      videoBindQuList({ id: id })
        .then(res => {
          this.bindQuList = res.data;
          this.loading = false;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    /** 题目解绑 */
    handleVideoQuRemove(row) {
      let query = {
        id: this.id,
        objId: row.objId
      };
      videoDelQu(query)
        .then(res => {
          this.$modal.msgSuccess("解绑成功");
          this.getBindQuList(this.id);
        })
        .finally(() => {});
    },
    /** 未绑定题目列表 */
    handleUnBindQuList() {
      this.question.unBind = true;
      this.getUnBindQuList();
    },
    getUnBindQuList() {
      this.loading = true;
      videoUnBindQuList(this.unBindQuQuery)
        .then(res => {
          this.unBindQuList = res.data.rows;
          this.unBindQuTotal = res.data.total;
          this.loading = false;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    /** 更改题目类型 */
    changeUnBindQuType() {
      this.getUnBindQuList();
    },
    /** 更改难度等级 */
    changeUnBindQuGrand() {
      this.getUnBindQuList();
    },
    /** 搜索 */
    handleQueryUnBindQu() {
      this.getUnBindQuList();
    },
    /** 重置 */
    resetUnBindQuQuery() {
      this.resetForm("unBindQuQueryForm");
      this.unBindQuQuery.quGrand = undefined;
      this.unBindQuQuery.quType = undefined;
      this.unBindQuQuery.pageNum = 1;
      this.getUnBindQuList();
    },
    /** 绑定 */
    handleVideoQuAdd(objId) {
      this.secondSelect = true;
      this.second = 0;
      this.objId = objId;
    },
    cancelAddQu() {
      this.secondSelect = false;
      this.second = 0;
    },
    submitAddQu() {
      let query = {
        id: this.id,
        objId: this.objId,
        second: this.second
      };
      videoAddQu(query)
        .then(res => {
          this.secondSelect = false;
          this.getBindQuList(this.id);
          this.getUnBindQuList();
        })
        .finally(() => {
          this.secondSelect = false;
        });
    },
    /** 题目详情 */
    handleQuInfo(row) {
      this.infoDialog.objData = row;
      this.infoDialog.objShow = true;
    }
  }
};
</script>

<style scoped>
.videoImg {
  display: block;
  margin: auto;
  width: 120px;
  height: 60px;
}
.bindBtn {
  margin: 0 0 20px 20px;
}
</style>
